package cn.witque.controller;


import cn.witque.pojo.ItripHotel;
import cn.witque.pojo.dto.Dto;
import cn.witque.pojo.vo.ItripLabelDicVO;
import cn.witque.pojo.vo.comment.CommentListVO;
import cn.witque.pojo.vo.comment.CommentScoreVO;
import cn.witque.pojo.vo.comment.SearchCommentVo;
import cn.witque.pojo.vo.hotel.ImageVo;
import cn.witque.service.CommentService;
import cn.witque.service.HotelService;
import cn.witque.service.ItripImageService;
import cn.witque.service.ItripLabelService;
import cn.witque.utils.*;
import cn.witque.pojo.vo.AddCommentVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;


import cn.witque.pojo.ItripComment;
import cn.witque.pojo.ItripImage;
import cn.witque.pojo.ItripUser;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
@RequestMapping("/api/comment")
public class CommentController {


    @Resource
    private HotelService hotelService;


    @Resource
    private ItripLabelService itripLabelService;


    @Resource
    private CommentService commentService;


    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SystemConfig systemConfig;

    @Resource
    private ItripImageService itripImageService;


    /**
     * 根据map查询数量
     * @param map
     * @return
     */
    private Integer getCommentCountByMap(Map<String,Object> map){
        Integer count = commentService.getCommentCountByMap(map);
        return count;
    }


    /**
     * 分页获取评论列表
     * @param searchCommentVo
     * @return
     */
    @RequestMapping(value = "/getcommentlist",method=RequestMethod.POST)
    @ResponseBody
    public Dto getcommentlist (@RequestBody SearchCommentVo searchCommentVo){

        if (EmptyUtil.isEmpty(searchCommentVo.getHotelId())){
            return DtoUtil.getFailed("酒店id不能为空","126");
        }

        if(searchCommentVo.getIsOk() == -1){
            searchCommentVo.setIsOk(null);
        }

        if (searchCommentVo.getIsHavingImg() == -1){
            searchCommentVo.setIsHavingImg(null);
        }

        try {
            Map<String,Object> map = new HashMap<>();
            map.put("hotelId",searchCommentVo.getHotelId());
            map.put("isHavingImg",searchCommentVo.getIsHavingImg());
            map.put("isOk",searchCommentVo.getIsOk());
            Integer totalCount = this.getCommentCountByMap(map);

            Page page = new Page(searchCommentVo.getPageNo(),searchCommentVo.getPageSize(),totalCount);
            map.put("pageIndex",page.getBeginPos());
            map.put("pageSize",page.getPageSize());

            List<CommentListVO> list = commentService.getCommentListByMap(map);
            page.setRows(list);

            return DtoUtil.getSuccess("获取评论列表成功！",page);

        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.getFailed("获取评论列表失败！","136");
        }

    }

    /**
     * 根据酒店ID查各项评分
     * @param hotelId
     * @return
     */
    @RequestMapping(value = "/gethotelscore/{hotelId}",method=RequestMethod.GET)
    @ResponseBody
    public Dto getHotelScore(@PathVariable Long hotelId){
        if (EmptyUtil.isEmpty(hotelId)){
            return DtoUtil.getFailed("酒店ID不能为空","126");
        }

        CommentScoreVO commentScoreVO = commentService.getAllScore(hotelId);
        if (EmptyUtil.isEmpty(commentScoreVO)){
            return DtoUtil.getFailed("获取酒店评分失败！","138");
        }
        return DtoUtil.getSuccess("获取酒店评分成功！",commentScoreVO);
    }

    /**
     * 根据酒店id查询各种评论的数量
     * @param hotelId
     * @return
     */
    @RequestMapping(value = "/getcount/{hotelId}",method=RequestMethod.GET)
    @ResponseBody
    public Dto getCommentCountByType(@PathVariable Long hotelId){
        if (EmptyUtil.isEmpty(hotelId)){
            return DtoUtil.getFailed("酒店ID不能为空","126");
        }
        Map<String,Object> allCountMap = new HashMap<>();
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("hotelId",hotelId);
        Integer count = 0;
        count = this.getCommentCountByMap(paramMap);
        if (count != -1){
            allCountMap.put("allcomment",count);
        }else {
            return DtoUtil.getFailed("获取酒店总评论数失败！","137");
        }
        /**
         * isOk表示是否有待改善  1为值得推荐 0为有待改善
         */
        paramMap.put("isOk",1);
        count = this.getCommentCountByMap(paramMap);
        if (count != -1){
            allCountMap.put("isok",count);
        }else {
            return DtoUtil.getFailed("获取值得推荐评论数失败！","137");
        }


        paramMap.put("isOk",0);
        count = this.getCommentCountByMap(paramMap);
        if (count != -1){
            allCountMap.put("improve",count);
        }else {
            return DtoUtil.getFailed("获取有待改善评论数失败！","137");
        }

        paramMap.put("isOk",null);
        /**
         * isHavingImg 0为无图片 1为有图片
         */
        paramMap.put("isHavingImg",1);
        count = this.getCommentCountByMap(paramMap);
        if (count != -1){
            allCountMap.put("havingimg",count);
        }else {
            return DtoUtil.getFailed("获取有图片评论数失败！","137");
        }

        return DtoUtil.getSuccess("获取各评论数量成功！",allCountMap);
    }


    /**
     * 获取点评页的出游类型列表
     * @return
     */
    @RequestMapping(value = "/gettraveltype",method=RequestMethod.GET)
    @ResponseBody
    public Dto getTravelType(){
        List<ItripLabelDicVO> list = itripLabelService.getItripLabelDicByParentId(107L);

        if (EmptyUtil.isEmpty(list) || list.size()<1){
            return DtoUtil.getFailed("获取出游类型失败！","135");
        }

        return DtoUtil.getSuccess("获取出游类型成功",list);
    }

    /**
     * 获取点评页的酒店信息
     * @param hotelId
     * @return
     */
    @RequestMapping(value = "/gethoteldesc/{hotelId}",method=RequestMethod.GET,produces = "application/json")
    @ResponseBody
    public Dto getHotelDesc(@PathVariable Long hotelId){

        if(EmptyUtil.isEmpty(hotelId)){
            return DtoUtil.getFailed("酒店id不能为空","126");
        }

        ItripHotel itripHotel = hotelService.selectByPrimaryKey(hotelId);
        if (EmptyUtil.isEmpty(itripHotel)){
            return DtoUtil.getFailed("获取酒店信息失败！","134");
        }

        return DtoUtil.getSuccess("获取酒店信息成功!",itripHotel);
    }


    /**
     * 查询评论图片
     * @param targetId
     * @return
     */
    @RequestMapping(value = "/getimg/{targetId}",method=RequestMethod.GET)
    @ResponseBody
    public Dto getImgByTargetId(@PathVariable String targetId){

        if (EmptyUtil.isEmpty(targetId)){
            return DtoUtil.getFailed("酒店id不能为空","126");
        }
        Map<String, String> param = new HashMap<>();
        param.put("type", "2");
        param.put("targetId", targetId);
        List<ImageVo> list = hotelService.getImageByMap(param);

        if (list.size()<1){
            return DtoUtil.getFailed("获取评论图片失败！","127");
        }
        return DtoUtil.getSuccess("获取评论图片列表成功！",list);
    }


    /**
     * 新增酒店点评
     * @param addCommentVo
     * @param request
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto addComment(@RequestBody AddCommentVo addCommentVo, HttpServletRequest request){
        String token = request.getHeader("token");
        ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(token);
        if (itripUser!=null && addCommentVo !=null){
            if (addCommentVo.getOrderId()==null){
                return DtoUtil.getFailed("订单ID为空","189");
            }
            ItripComment itripComment=new ItripComment();
            itripComment.setHotelId(addCommentVo.getHotelId());
            itripComment.setOrderId(addCommentVo.getOrderId());
            itripComment.setProductId(addCommentVo.getProductId());
            itripComment.setProductType(addCommentVo.getProductType());
            itripComment.setUserId(itripUser.getId());
            itripComment.setIsHavingImg(addCommentVo.getIsHavingImg());
            itripComment.setPositionScore(addCommentVo.getPositionScore());
            itripComment.setFacilitiesScore(addCommentVo.getFacilitiesScore());
            itripComment.setServiceScore(addCommentVo.getServiceScore());
            itripComment.setHygieneScore(addCommentVo.getHygieneScore());
            itripComment.setIsOk(addCommentVo.getIsOk());
            itripComment.setTripMode(addCommentVo.getTripMode());
            itripComment.setCreationDate(new Date());
            itripComment.setCreatedBy(itripUser.getId());
            itripComment.setContent(addCommentVo.getContent());
            List<ItripImage> itripImages=null;
            if (addCommentVo.getIsHavingImg()==1){
                itripImages=new ArrayList<ItripImage>();
                int i=1;
                for (ItripImage itripImage:addCommentVo.getItripImages()){
                    itripImage.setPosition(i);
                    itripImage.setCreationDate(new Date());
                    itripImage.setCreatedBy(itripUser.getId());
                    itripImage.setType("2");
                    itripImages.add(itripImage);
                    i++;
                }
            }
            if (commentService.insert(itripComment,itripImages)){
                return DtoUtil.getSuccess("点评成功");
            }else {
                return DtoUtil.getFailed("点评失败","188");
            }
        } else if (itripUser != null && addCommentVo == null) {
            return DtoUtil.getFailed("评论内容不能为空", "187");
        } else {
            return DtoUtil.getFailed("用户信息失效，请重新登录", "186");
        }
    }


    /**
     * 酒店点评的图片增加功能
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Dto uploadPic(HttpServletRequest request,HttpServletResponse response) {
        List<String> list=new ArrayList<String>();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            int count = multipartHttpServletRequest.getFileMap().size();
            if (count > 0 && count <= 4) {
                String token = multipartHttpServletRequest.getHeader("token");
                ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(token);
                if (itripUser != null) {
                    Iterator iterator = multipartHttpServletRequest.getFileNames();
                    while (iterator.hasNext()) {
                        MultipartFile file = multipartHttpServletRequest.getFile(String.valueOf(iterator.next()));
                        if (file != null) {
                            String fileName = file.getOriginalFilename();
                            String prefix = FilenameUtils.getExtension(fileName);
                            if (fileName.trim() != "" && (prefix.equalsIgnoreCase("jpg") ||
                                    prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg")
                                    || prefix.equalsIgnoreCase("pneg"))) {
                                String newFileName = itripUser.getId() + "-" + System.currentTimeMillis() + "-" + (int) (Math.random() * 10000000) + "." + prefix;
                                String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"upload");
                                File targetFile = new File(path,newFileName);
                                try {
                                    file.transferTo(targetFile);
                                    String linuxPath=systemConfig.getFileUploadPathLinux();
                                    SFTPUtil sftpUtil=SFTPUtil.getInstance();
                                    sftpUtil.upload(linuxPath,path+"/"+newFileName);
                                    list.add(systemConfig.getVisitImgUrlString()+newFileName);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                return DtoUtil.getSuccess("文件上传成功",list);
                            } else {
                                return DtoUtil.getFailed("文件不存在", "183");
                            }
                        }
                    }
                } else {
                    return DtoUtil.getFailed("用户信息失效，请重新登录", "186");
                }
            } else {
                return DtoUtil.getFailed("文件的上传个数超出限制", "184");
            }
        }
        return DtoUtil.getFailed("没有检测到文件上传", "185");
    }


    /**
     * 酒店点评的图片删除
     * @param imgName
     * @param request
     * @return
     */
    @RequestMapping(value = "/delpic",method = RequestMethod.POST)
    @ResponseBody
    public Dto delIpc(@RequestParam String imgName,HttpServletRequest request){
        String token = request.getHeader("token");
        ItripUser itripUser = (ItripUser) redisTemplate.opsForValue().get(token);
        if (itripUser != null){
            String path=systemConfig.getFileUploadPathLinux();
            SFTPUtil sftpUtil=new SFTPUtil();
            sftpUtil.delete(path,path+"/"+imgName);
            return DtoUtil.getSuccess("删除成功");
        }
        return DtoUtil.getFailed("用户信息失效，请重新登录", "186");
    }

}